<?php
/**********************
**login.inc
**Date Created: 4/13/2009
**Copyright 2009 Tomorrow Tech Industries
**Contact: RPITomorrowTech@gmail.com
**********************/

require_once("private/bottom.inc");
require_once("private/dba.inc");
require_once("private/user.inc");

//Query used in URL passing
define('QUERY_LOGIN_DENY', 'denyReason');

//Return codes from confirmUser
define('LOGIN_OK', 0);
define('INVALID_USER', 1);
define('INVALID_PASSWORD', 2);
define('DB_ERROR', 3);

define('SESSION_USER_NAME', 'userName');
define('SESSION_PASSWORD', 'password');

define('USER_NAME_MAX_LENGTH', 24);

/**
 * Checks whether or not the given username is in the
 * database, if so it checks if the given password is
 * the same password in the database for that user.
 * If the user doesn't exist or if the passwords don't
 * match up, it returns an error code (1 or 2). 
 * On success it returns 0.
 */
function confirmUser($username, $passwordHash)
{
	$user = new User($username, $rc);
	if( TT_FAILED($rc) )
	{
		return INVALID_USER;
	}
	$rc = $user->isPasswordCorrectByHash($passwordHash);
	if( TT_SUCCEEDED($rc) )
	{
		return LOGIN_OK;
	}
	else if( $rc == TT_ACCESS )
	{
		return INVALID_PASSWORD;
	}
	else
	{
		return DB_ERROR;
	}
}

/**
* checkLogin - Checks if the user has already previously
* logged in, and a session with the user has already been
* established. Also checks to see if user has been remembered.
* If so, the database is queried to make sure of the user's 
* authenticity. Returns true if the user has logged in.
*/
function checkLogin()
{
	//Throw away the reason parameter
	return isUserLoggedIn($reason);
}

/***
Should be the first function called on most pages
Performs a redirect or other action necessary if user is not logged in
***/
function enforceLoggedIn()
{
	if( !isUserLoggedIn($reason) )
	{
		//Do the redirect
		enforceNotLoggedIn($reason);
	}
}

function isUserLoggedIn(&$reason)
{
	/**
	 * Checks to see if the user has submitted his
	 * username and password through the login form,
	 * if so, checks authenticity in database and
	 * creates session.
	 */
	//FIXME: why doesn't this work?
	//if( !isset($_COOKIE["PHPSESSID"]) )
	{
		session_start();
	}
	if( isset($_POST['sublogin']) )
	{
		//Check that all fields were typed in
		if( !$_POST['user'] || !$_POST['pass'] )
		{
			$reason = 'You didn\'t fill in a required field.';
			return false;
		}
		//Spruce up username, check length
		$_POST['user'] = trim($_POST['user']);
		if( strlen($_POST['user']) > USER_NAME_MAX_LENGTH )
		{
		    $reason = "Sorry, the username is longer than 24 characters, please shorten it.";
			return false;
		}

		//Username and password correct, register session variables
		$_POST['user'] = stripslashes($_POST['user']);
		$_SESSION[SESSION_USER_NAME] = $_POST['user'];
		$_SESSION[SESSION_PASSWORD] = User::computeHash($_POST['pass']);

		/**
		* This is the cool part: the user has requested that we remember that
		* he's logged in, so we set two cookies. One to hold his username,
		* and one to hold his md5 encrypted password. We set them both to
		* expire in 100 days. Now, next time he comes to our site, we will
		* log him in automatically.
		*/
		if( isset($_POST['remember']) )
		{
		    setcookie("cookname", $_SESSION[SESSION_USER_NAME], time()+60*60*24*100, "/");
		    setcookie("cookpass", $_SESSION[SESSION_PASSWORD], time()+60*60*24*100, "/");
		}
	}
	//Check if user has been remembered
	else if( isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass']) )
	{
		$_SESSION[SESSION_USER_NAME] = $_COOKIE['cookname'];
		$_SESSION[SESSION_PASSWORD] = $_COOKIE['cookpass'];
	}
	//Should be a session var then, if not abort
	if( !isset($_SESSION[SESSION_USER_NAME]) || !isset($_SESSION[SESSION_PASSWORD]) )
	{
		$reason = "Not logged in";
		return false;
	}

	$userName = $_SESSION[SESSION_USER_NAME];
	$passwordHash = $_SESSION[SESSION_PASSWORD];
	//Checks that username is in database and password is correct
	$result = confirmUser($userName, $passwordHash);
	//Check error codes
	if( $result == DB_ERROR )
	{
		unset($_SESSION[SESSION_USER_NAME]);
		unset($_SESSION[SESSION_PASSWORD]);
		$reason = 'Internal database error.';
		return false;
	}
	else if( $result == INVALID_USER )
	{
		unset($_SESSION[SESSION_USER_NAME]);
		unset($_SESSION[SESSION_PASSWORD]);
		$reason = "That username doesn't exist in our database.";
		return false;
	}
	else if( $result == INVALID_PASSWORD )
	{
		unset($_SESSION[SESSION_USER_NAME]);
		unset($_SESSION[SESSION_PASSWORD]);
	    $reason = 'Incorrect password, please try again.';
		return false;
	}

	//Nothing went wrong and we appear valid, so return true
	return true;
}

/********
User is not logged in and must be redirected to login screen
********/
function enforceNotLoggedIn($reason)
{
	//Does reason need ' ' => '%20' conversions?
	//echo 'Not logged in.';
	$URL="index.php?" . QUERY_LOGIN_DENY . "=" . $reason;

    header("Location: $URL");
    //Code execution should not reach further 
	die("You should be redirected momentarily. If not, click <A href=\"" . $URL . "\">here</A>.");
}


?>
